<template lang="pug">
  div.box(data-logig)
    img(src="/static/images/login-bg.jpg").imgs
    img(src="/static/images/login-title.png").imgTitle
    div.boxCenter
      div.boxCenterSon
        el-form.loginForm(v-model="loginForm" ref="loginForm" v-bind:rules="rules"
        v-bind:show-message="false")
          div.input
            el-form-item.kalix-form-item(prop="name")
              img(src="/static/images/login-user.jpg")
              input(placeholder="请输入用户名" v-model="loginForm.name"  ref="loginFormName")
          div.input
            el-form-item.kalix-form-item(prop="pass")
              img(src="/static/images/login-password.png")
              input(type="password" v-model="loginForm.pass" ref="loginFormPass" placeholder="请输入密码")
          div
            input(type="checkbox" v-model="checked")
            span(style="font-size:16px") 记住密码
          el-form-item(label="")
            div.boxButton(@click="onSubmit()" @keydown="onSubmit()") 登录
          //el-button
    div.bottom
</template>

<script>
  import Login from '../../api/login'
  import Message from '../../components/corelib/common/message'
  import {logoutUrl, applicationURL, baseURL} from '../../config/global.toml'
  import {mapMutations} from 'vuex'

  export default {
    name: 'login',
    data() {
      return {
        checked: false,
        loginForm:
          {
            name: '',
            pass: ''
          },
        rules: {
          name: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 2, max: 8, message: '用户名长度在 2 到 8 个字符', trigger: 'blur'}
          ],
          pass: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ]
        },
        error: {
          flag: false,
          message: ''
        }
      }
    },
    activated() {
      this.loginForm = {name: '', pass: ''}
    },
    mounted() {
      let accessToken = this.$KalixCatch.get('access_token')
      if (accessToken && accessToken.length) {
        this.$http.get(logoutUrl)
          .then(res => {
          })
      }
      this.tabInput()
      let passworld = localStorage.getItem('checked')
      if (passworld === 'true') {
        this.loginForm.name = localStorage.getItem('uname')
        this.loginForm.pass = localStorage.getItem('upass')
        this.checked = passworld
      }
    },
    methods: {
      ...mapMutations({
        setCurrentUser: 'setCurrentUser',
        setMenuList: 'setMenuList',
        setNavigateTreeData: 'setNavigateTreeData'
      }),
      onSubmit(formName) {
        if (this._validateForm()) {
          this.login()
        }
      },
      login(callback) {
        //  登录
        Login.remoteLogin({
          'username': this.loginForm.name,
          'password': this.loginForm.pass
        }).then(data => {
          console.log('data', data)
          if (data.success) {
            Message.success(data.message)
            this.$KalixCatch.save('id', data.user.id)
            this.$KalixCatch.save('access_token', data.access_token)
            this.$KalixCatch.save('user_token', data.user.token)
            this.$KalixCatch.save('user_name', data.user.name)
            this.$KalixCatch.save('loginname', this.loginForm.name)
            this.$KalixCatch.save('loginpass', this.loginForm.pass)
            if (this.checked) {
              localStorage.setItem('checked', this.checked)
              localStorage.setItem('uname', this.loginForm.name)
              localStorage.setItem('upass', this.loginForm.pass)
            } else {
              localStorage.setItem('checked', this.checked)
            }
            this.axios.request({
              method: 'GET',
              url: baseURL + '/camel/rest/users?jsonStr=&page=1&start=0&limit=10&otherStr='
            }).then((res) => {
              this.$KalixCatch.save('personal', JSON.stringify(res.data.data))
            })
            this.axios.request({
              method: 'GET',
              url: '/camel/rest/users/' + data.user.id + '?id=' + data.user.id
            }).then((res) => {
              this.$KalixCatch.save('personaltwo', JSON.stringify(res.data.data))
              let className = res.data.data[0]
              if (className.identity === '管理专家' && className.className === '组织病理') {
                this.$router.push({path: '/expertOrg'})
              } else if (className.identity === '管理专家' && className.className === '细胞病理') {
                this.$router.push({path: '/expertCell'})
              } else {
                this.$router.push({path: '/expertOrg'})
              }
            })
          } else {
            this.$refs.loginFormName.focus()
            Message.error(data.message)
          }
        }).catch(error => {
          this.$refs.loginFormName.focus()
          this.$KalixMessage.error(error.message)
        })
      },
      _validateForm() {
        //  验证表单
        for (let key in this.rules) {
          this.error.flag = false
          this.error.message = ''
          this.$refs.loginForm.validateField(key, errorMessage => {
            //  如果错误信息长度 > 0 表示验证不通过
            this.error.flag = errorMessage.length > 0
            this.error.message = errorMessage
          })
          if (this.loginForm.name === '' || this.loginForm.pass === '') {
            Message.error('请输入账号或密码')
            return false
          }
        }
        return true
      },
      tabInput() {
        let ipts = document.getElementsByClassName('el-input__inner')
        for (let i = 0; i < ipts.length; i++) {
          ipts[i].addEventListener('keydown', e => {
            if (e.keyCode === 13) {
              if (ipts[i + 1]) {
                ipts[i + 1].focus()
              } else {
                document.getElementsByClassName('btn-submit')[0].focus()
              }
            }
          })
        }
      },
      listen() {
        this.error.flag = false
      },
      _getMenu(callBack) {
        this.treeListData = {}
        this.menu = []
        this.$http.get(applicationURL, {
          params: {
            _dc: (new Date()).getTime(),
            page: 1,
            start: 0,
            limit: 25
          }
        }).then(res => {
          if (res && res.data) {
            this.menu = res.data
            this.setMenuList(this.menu)
            this.setList(0, () => {
              this.setNavigateTreeData(this.treeListData)
              callBack()
            })
          }
        })
      },
      setList(index, callBack) {
        if (index < this.menu.length) {
          let item = this.menu[index]
          let key = item.id
          let _treeData = []
          this.$http.get(`${applicationURL}/${key}`,
            {
              params: {
                _dc: (new Date()).getTime(),
                node: 'root'
              }
            })
            .then(res => {
              if (res.data && res.data.code !== 401) {
                _treeData = res.data
                _treeData.map(e => {
                  this.$set(e, 'isShow', false)
                })
                this.treeListData[key] = _treeData
                this.setList(index += 1, callBack)
              }
            })
        } else {
          callBack()
        }
      }
    },
    computed: {},
    watch: {
      loginForm: {
        handler: 'listen',
        // 深度观察
        deep: true
      }
    }
  }
</script>

<style scoped lang="stylus">
  .box
    width 100%
    height 100%
    position relative

  .imgs
    width 100%
    height 46%

  .imgTitle
    position absolute
    top 22%
    left 50%
    transform translateX(-50%)

  .boxCenter
    width 548px
    height 424px
    position absolute
    left 50%
    top 64%
    transform translateX(-50%)
    margin-top -212px
    background-color #fff
    padding-top 50px
    box-sizing border-box
    box-shadow 3px 3px 10px #919191
    border-radius 5px

  .boxCenterSon
    width 402px
    margin 0 auto

  .input
    width 402px
    height 60px
    line-height 60px
    border-bottom 1px solid #E8E8E8
    margin-bottom 32px
    img
      width 24px
      height 24px
    input
      margin-left 24px
      width 350px
      height 40px
      font-size 16px

  .boxButton
    width 400px
    height 54px
    line-height 54px
    background-color #1269DB
    text-align center
    letter-spacing 10px
    font-size 18px
    color #fff
    margin-top 32px
    cursor pointer

  .bottom
    width 100%
    height 60px
    position absolute
    left 0
    bottom 0
    background-color #1269DB
</style>
